package org.example.commodity.activity.timertask;

import org.example.commodity.activity.entity.ActivityInfo;
import org.example.commodity.activity.timertask.processor.ICommodityActivityEndProcessor;
import org.example.commodity.activity.timertask.processor.ICommodityActivityStartProcessor;
import org.example.timertask.BaseTimerTaskStartConfiguration;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

public abstract class BaseCommodityActivityStartConfiguration<T extends ActivityInfo> extends BaseTimerTaskStartConfiguration<T> {

    private final ICommodityActivityEndProcessor<T> activityEndProcessor;
    private final ICommodityActivityStartProcessor<T> activityStartProcessor;

    public BaseCommodityActivityStartConfiguration(ICommodityActivityEndProcessor<T> offProcessor,
                                                   ICommodityActivityStartProcessor<T> startProcessor) {
        this.endProcessor = offProcessor;
        this.startProcessor = startProcessor;
        this.activityEndProcessor = offProcessor;
        this.activityStartProcessor = startProcessor;
    }

    @Override
    public void configProcessor() {
    }


    @Override
    public boolean isUnStart(LocalDateTime now, T item) {
        return item.getStartTime().isAfter(now);
    }

    @Override
    public boolean isStarting(LocalDateTime now, T item) {
        return item.getStartTime().isBefore(now) && item.getEndTime().isAfter(now);
    }

    @Override
    public boolean isEnded(LocalDateTime now, T item) {
        return item.getEndTime().isBefore(now);
    }

    @Override
    public void addOnTimerTask(LocalDateTime now, T item) {
        BaseCommodityActivityStartTimerTask<T> timerTask = getStartTimerTask(item.getId(), this.activityStartProcessor);
        long delaySeconds = Duration.between(now, item.getStartTime()).toSeconds();
        this.hashedWheelTimer.newTimeout(timerTask, delaySeconds, TimeUnit.SECONDS);
    }

    protected abstract BaseCommodityActivityStartTimerTask<T> getStartTimerTask(Long activityId, ICommodityActivityStartProcessor<T> activityStartProcessor);
    @Override
    public void addOffTomerTask(LocalDateTime now, T item) {
        this.activityStartProcessor.startActivity(item.getId());
        BaseCommodityActivityEndTimerTask<T> timerTask = getEndTimerTask(item.getId(),this.activityEndProcessor);
        long delaySeconds = Duration.between(LocalDateTime.now(), item.getEndTime()).toSeconds();
        hashedWheelTimer.newTimeout(timerTask, delaySeconds, TimeUnit.SECONDS);
    }
    protected abstract BaseCommodityActivityEndTimerTask<T> getEndTimerTask(Long activityId, ICommodityActivityEndProcessor<T> activityEndProcessor);
}
